package cn.hhhy.service.impl;

import cn.hhhy.mapper.CouponMapper;
import cn.hhhy.mapper.OrderMapper;
import cn.hhhy.pojo.Coupon;
import cn.hhhy.pojo.Order;
import cn.hhhy.pojo.PageResult;
import cn.hhhy.pojo.QueryPageBean;
import cn.hhhy.service.CouponService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CouponServiceImpl implements CouponService {

    @Autowired
    private CouponMapper couponMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Override
    public PageResult findPage(QueryPageBean pageBean) {
        Integer currentPage = pageBean.getCurrentPage();
        Integer pageSize = pageBean.getPageSize();
        String queryString = pageBean.getQueryString();

        IPage<Coupon> page = couponMapper.selectPage(new Page<>(currentPage,pageSize),
                Wrappers.lambdaQuery(Coupon.class)
                        .like(!Strings.isEmpty(queryString), Coupon::getUid, queryString)
                        .or()
                        .like(!Strings.isEmpty(queryString), Coupon::getOid, queryString)
                        .or()
                        .like(!Strings.isEmpty(queryString), Coupon::getCname, queryString)
                        .or()
                        .like(!Strings.isEmpty(queryString), Coupon::getCabout, queryString)
        );
        return new PageResult(page.getTotal(), page.getRecords());
    }

    @Override
    public Coupon findById(Integer id) {
        return couponMapper.selectById(id);
    }

    @Override
    public void add(Coupon coupon) {
        couponMapper.insert(coupon);
    }

    @Override
    public void delete(Integer id) {
        couponMapper.deleteById(id);
    }

    @Override
    public void update(Coupon coupon) {
        couponMapper.updateById(coupon);
    }

    @Override
    public List<Coupon> findByUID(Integer id) {
        return couponMapper.selectList(Wrappers.lambdaQuery(Coupon.class).eq(Coupon::getUid,id));
    }

    @Override
    public void useDiscount(Coupon coupon) {
        Order order = orderMapper.selectById(coupon.getOid());
        Coupon c = couponMapper.selectById(coupon.getCid());

        c.setState(1);
        c.setOid(coupon.getOid());

        Double price = order.getPrice();
        if (c.getPreferenceType() == 0) {
            price *= c.getDiscountAmount();
        } else if(c.getPreferenceType() == 1) {
            price -= c.getDiscountAmount();
            if (price < 0) price = 0.0;
        }

        order.setPrice(price);

        orderMapper.updateById(order);
        couponMapper.updateById(c);
    }
}
